package com.hjwoo.app.views;

import android.os.Build;
import android.os.Bundle;
import android.os.Handler;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentActivity;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentTransaction;
import android.support.v4.view.ViewCompat;
import android.text.TextUtils;
import android.util.Log;
import android.view.KeyEvent;
import android.view.View;
import android.view.ViewGroup;
import android.view.Window;
import android.view.WindowManager;
import android.widget.RadioGroup;

import com.hjwoo.app.R;
import com.hjwoo.app.been.UserAccessTokenOBJ;
import com.hjwoo.app.common.LoanApplication;
import com.hjwoo.app.fragment.DiscoverFragment;
import com.hjwoo.app.fragment.HomeFragment;
import com.hjwoo.app.fragment.LeadsFragment;
import com.hjwoo.app.fragment.UserCenterFragment;
import com.hjwoo.app.utils.DoubleClickExitHelper;
import com.hjwoo.app.utils.LoanAccessTokenIdKeeper;
import com.hjwoo.app.utils.LoanToast;
import com.hjwoo.app.utils.Utils;
import com.umeng.message.PushAgent;
import com.umeng.message.UmengRegistrar;

import java.util.ArrayList;
import java.util.Arrays;

public class MainActivity extends FragmentActivity {
    private static final String TAG = MainActivity.class.getSimpleName();
    private static final String FRAGMENT_TAGS = "fragmentTags";
    private static final String CURR_INDEX = "currIndex";
    public static MainActivity instance;
    public static int currIndex = 0;

    public static RadioGroup group;

    public static ArrayList<String> fragmentTags;
    public static FragmentManager fragmentManager;
    String deviceId;
    //双击退出
    private DoubleClickExitHelper mDoubleClickExit;

    public static void showFragment() {
        //        if (currIndex == 3) {
        //            UIHelper.showLogin(MainActivity.this);
        //        }

        FragmentTransaction fragmentTransaction = fragmentManager.beginTransaction();
        Fragment fragment = fragmentManager.findFragmentByTag(fragmentTags.get(currIndex));
        if (fragment == null) {
            fragment = instantFragment(currIndex);
        }
        for (int i = 0; i < fragmentTags.size(); i++) {
            Fragment f = fragmentManager.findFragmentByTag(fragmentTags.get(i));
            if (f != null && f.isAdded()) {
                fragmentTransaction.hide(f);
            }
        }
        if (fragment.isAdded()) {
            fragmentTransaction.show(fragment);
        } else {
            fragmentTransaction.add(R.id.fragment_container, fragment, fragmentTags.get(currIndex));
        }
        fragmentTransaction.commitAllowingStateLoss();
        fragmentManager.executePendingTransactions();
    }

    public static Fragment instantFragment(int currIndex) {
        switch (currIndex) {
            case 0:
                return new HomeFragment();
            case 1:
                return new LeadsFragment();
            case 2:
                return new DiscoverFragment();
            case 3:
                return new UserCenterFragment();
            default:
                return null;
        }
    }

    /**
     * 获取app的deviceId
     */
    private void initUMeng() {

        new Handler().postDelayed(new Runnable() {

            @Override
            public void run() {

                do {
                    deviceId = UmengRegistrar.getRegistrationId(MainActivity.this);

                    Log.e("token", "deviceId:" + deviceId + "结束");
                    try {
                        Thread.sleep(1000);
                    } catch (InterruptedException e) {
                        // TODO 自动生成的 catch 块
                        e.printStackTrace();
                    }
                }
                while (TextUtils.isEmpty(deviceId));
            }
        }, 1000);
    }


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

//        requestWindowFeature(Window.FEATURE_NO_TITLE);//去除自带标题栏
//        getWindow().addFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS);//沉浸状态栏
        // 修改状态栏颜色，4.4+生效
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
            Window window = getWindow();
//设置透明状态栏,这样才能让 ContentView 向上
            window.addFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS);
//需要设置这个 flag 才能调用 setStatusBarColor 来设置状态栏颜色
            window.addFlags(WindowManager.LayoutParams.FLAG_DRAWS_SYSTEM_BAR_BACKGROUNDS);
//设置状态栏颜色
            window.setStatusBarColor(getResources().getColor(R.color.status_bar_bg));
        }

        ViewGroup mContentView = (ViewGroup) findViewById(Window.ID_ANDROID_CONTENT);
        View mChildView = mContentView.getChildAt(0);
        if (mChildView != null) {
            //注意不是设置 ContentView 的 FitsSystemWindows, 而是设置 ContentView 的第一个子 View . 使其不为系统 View 预留空间.
            ViewCompat.setFitsSystemWindows(mChildView, false);
        }

        setContentView(R.layout.activity_main);
                                /* 注意: 此方法请务必调用！
                        如果不调用此方法，不仅会导致按照"几天不活跃"条件来推送失效，
                        还将导致广播发送不成功以及设备描述红色等问题发生。
                        可以只在应用的主Activity中调用此方法，
                        但是由于SDK的日志发送策略，
                        有可能由于主activity的日志没有发送成功，而导致未统计到日活数据。
                        */
        //        PushAgent.getInstance(this).onAppStart();

        //        在应用的主Activity onCreate() 函数中开启推送服务
        //        可以通过接口 mPushAgent.disable(); 来关闭客户端的通知服务。
        //        通过mPushAgent.isEnabled() 来查询状态。 状态表示有没有启用/关闭推送功能， 不表示推送后台服务的运行状态。
        PushAgent mPushAgent = PushAgent.getInstance(this);
        mPushAgent.enable();

        //        initUMeng();

        mPushAgent.setDebugMode(true);

        //开启推送并设置注册的回调处理
        //        mPushAgent.enable(new IUmengRegisterCallback() {
        //
        //            @Override
        //            public void onRegistered(final String registrationId) {
        //                new Handler().post(new Runnable() {
        //                    @Override
        //                    public void run() {
        //                        //onRegistered方法的参数registrationId即是device_token
        //                        Log.e("token", registrationId);
        //                        Log.e("token", "ceshi");
        //                    }
        //                });
        //            }
        //        });

        //        String device_token = UmengRegistrar.getRegistrationId(this);
        //        Log.e("token: ", "id:++++++++"+device_token);
        //
        //        Log.e("token", "ceshi3");

        // 关闭推送
        //        mPushAgent.disable();
        // 是否允许推送
        //        mPushAgent.isEnabled();


        mDoubleClickExit = new DoubleClickExitHelper(this);
        fragmentManager = getSupportFragmentManager();
        instance = MainActivity.this;
        Utils.initTitle("首页", instance, false);
        initData(savedInstanceState);
        initView();
    }

    @Override
    protected void onSaveInstanceState(Bundle outState) {
        super.onSaveInstanceState(outState);
        outState.putInt(CURR_INDEX, currIndex);
    }

    private void initData(Bundle savedInstanceState) {
        fragmentTags = new ArrayList<>(Arrays.asList("HomeFragment", "LeadsFragment", "DiscoverFragment", "UserCenterFragment"));
        currIndex = 0;
        if (savedInstanceState != null) {
            currIndex = savedInstanceState.getInt(CURR_INDEX);
            hideSavedFragment();
        }
    }

    private void hideSavedFragment() {
        Fragment fragment = fragmentManager.findFragmentByTag(fragmentTags.get(currIndex));
        if (fragment != null) {
            fragmentManager.beginTransaction().hide(fragment).commit();
        }
    }

    private void initView() {

        group = (RadioGroup) findViewById(R.id.group);
        group.setOnCheckedChangeListener(new RadioGroup.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(RadioGroup group, int checkedId) {
                switch (checkedId) {
                    case R.id.foot_bar_home:
                        currIndex = 0;
                        Utils.initTitle("首页", instance, false);
                        break;
                    case R.id.foot_bar_im:
                        UserAccessTokenOBJ userAccessTokenOBJ = LoanAccessTokenIdKeeper.readAccessToken(LoanApplication.getInstance());
                        if (!userAccessTokenOBJ.getAppSessionId().equals("")) {
//            登录状态
                            currIndex = 1;
                        } else {
//            退出状态
                            group.check(R.id.main_footbar_user);
                            LoanToast.showToastShort("请登录", MainActivity.instance);
                        }
                        break;
                    case R.id.foot_bar_interest:
                        currIndex = 2;
                        Utils.initTitle("发现", instance, false);
                        break;
                    case R.id.main_footbar_user:
                        currIndex = 3;
                        Utils.initTitle("我的", instance, false);
                        break;
                    default:
                        break;
                }
                showFragment();
            }
        });
        showFragment();
    }

    /**
     * 监听返回--是否退出程序
     */
    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {

        if (keyCode == KeyEvent.KEYCODE_BACK) {
            // 是否退出应用
            return mDoubleClickExit.onKeyDown(keyCode, event);
        }
        return super.onKeyDown(keyCode, event);
    }


    @Override
    protected void onRestart() {
        //        UserCenterFragment userCenterFragment = new UserCenterFragment();
        //        userCenterFragment.refreshLoginstatus();
        if (LeadsFragment.instance != null) {
            LeadsFragment.instance.getOrderList();
        }
        super.onRestart();
    }
}
